package com.sh.sales.happysales.ui.fragment;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sh.sales.happysales.R;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.app.utils.PreferenceUtil;
import com.sh.sales.happysales.base.BaseMessageEvent;
import com.sh.sales.happysales.webconfig.ActivityFunc;
import com.sh.sales.happysales.webconfig.EventType;
import com.sh.sales.happysales.webconfig.KnowledgeJs;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by zhouyucheng on 2017/9/15.
 */

public class ProfitFragment extends Fragment {
    @BindView(R.id.web_profit)
    WebView webProfit;
    Unbinder unbinder;
    private PreferenceUtil mPreferenceUtil;
    private String incomeUrl = "http://123.57.37.43:9001/happySell/index.html#/income";
    //  private String incomeUrl = "http://192.168.1.239:8085/static/happySell/index.html#/income";
    private String rankUrl = "http://123.57.37.43:9001/happySell/index.html#/rank";
    // private String rankUrl = "http://192.168.1.239:8085/static/happySell/index.html#/rank";
    private boolean isNeedBack = false; //是否需要返回

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_profit, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        init();
        //注册事件
        EventBus.getDefault().register(this);
        return inflate;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    private void init() {
        mPreferenceUtil = new PreferenceUtil(getActivity());
        webProfit.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        WebSettings webSettings = webProfit.getSettings();
        if (Build.VERSION.SDK_INT > 17) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);//不需要请求控制直接播放媒体文件
        }
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
        //使用localStorage则必须打开
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true); //兼容jw
        webSettings.setDatabaseEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);

        webSettings.setAppCacheMaxSize(1024 * 1024 * 2);//设置缓冲大小，我设的是8M
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        ActivityFunc func = new KnowledgeJs(getActivity());
//        webProfit.removeJavascriptInterface("searchBoxJavaBridge_");
        webProfit.addJavascriptInterface(func, "ActivityFunc");
        webProfit.loadUrl(incomeUrl);
        webProfit.setWebViewClient(new WebViewClient() { //腾讯内核缓存

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        webProfit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    // 监听到返回按钮点击事件
                    if (isNeedBack) {
                        isNeedBack = false;
                        EventBus.getDefault().post(new BaseMessageEvent(EventType.GoBack));
                    } else {
                        //自己的返回
                        LoginOutUtil.appDoublebtExit(getActivity());
                    }
                    return true;
                }
                return false;
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onJsEvent(BaseMessageEvent messageEvent) {
        if (messageEvent.getType() == EventType.GoBack) {
            isNeedBack = false;
            Observable.timer(50, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Long aLong) {
                    webProfit.loadUrl(incomeUrl);
                }
            });


        } else if (messageEvent.getType() == EventType.GoToRank) {
            isNeedBack = true;
            Observable.timer(50, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Long aLong) {
                    webProfit.loadUrl(rankUrl);
                }
            });


        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }
}
